//
//  PhotoSelectorViewController.swift
//  MyWeibo
//
//  Created by cat on 15/8/7.
//  Copyright © 2015年 cat. All rights reserved.
//

import UIKit

/// 可从用 cell
private let XBXPhotoSelectorViewCell = "XBXPhotoSelectorViewCell"
/// 最多允许选择照片的数量
private let kPhotoSelectorMaxCount = 9
class PhotoSelectorViewController: UICollectionViewController, PhotoSelectorViewCellDelegate {
    // 照片数组
    lazy var photos: [UIImage] = [UIImage]()
    // 当前用户选择的照片索引
    private var currentIndex = 0
    
    // MARK: - 构造函数
    init() {
        
        super.init(collectionViewLayout: UICollectionViewFlowLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView?.backgroundColor = UIColor.whiteColor()
        
        self.collectionView!.registerClass(PhotoSelectorViewCell.self, forCellWithReuseIdentifier: XBXPhotoSelectorViewCell)
        
        // 定义布局属性
        let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout
        
        layout?.itemSize = CGSize(width: 80, height: 80)
        layout?.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
    }
    
    // MARK: 数据源
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       
        return (photos.count == kPhotoSelectorMaxCount) ? photos.count : photos.count + 1

    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(XBXPhotoSelectorViewCell, forIndexPath: indexPath) as! PhotoSelectorViewCell
        
        cell.backgroundColor = UIColor.blueColor()
        
        cell.image = (indexPath.item < photos.count) ? photos[indexPath.item] : nil
        
        // 设置代理
        cell.photoDelegate = self
        
        return cell
    }
    
    // MARK: - PhotoSelectorViewCellDelegate
    
    private func photoSelectorViewCellRemovePhoto(cell: PhotoSelectorViewCell) {
        
        let indexPath = collectionView?.indexPathForCell(cell)
        
        // 删除数组中得对应项
        photos.removeAtIndex(indexPath!.item)
        
        collectionView?.reloadData()
    }
    
    private func photoSelectorViewCellSelectPhoto(cell: PhotoSelectorViewCell) {
        
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            print("无法访问照片库")
            return
        }
        
        let indexPath = collectionView?.indexPathForCell(cell)
        currentIndex = indexPath!.item
        
        let picker = UIImagePickerController()
        
        picker.delegate = self
        
        presentViewController(picker, animated: true, completion: nil)
    }
    

}

// MARK: - UIImagePickerControllerDelegate
extension PhotoSelectorViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        let img = image.scaleImage(300)
        
        if currentIndex == photos.count {
            
            photos.append(img)
            
        } else {
            
            photos[currentIndex] = img
        }
        
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}



// 写代理
private protocol PhotoSelectorViewCellDelegate: NSObjectProtocol {
    // 选择照片
    func photoSelectorViewCellSelectPhoto(cell: PhotoSelectorViewCell)
    // 删除照片
    func photoSelectorViewCellRemovePhoto(cell: PhotoSelectorViewCell)
    
}


private class PhotoSelectorViewCell: UICollectionViewCell {
    
    var image: UIImage? {
        didSet {
            if image == nil {
                
                photoButton.setImage("compose_pic_add")
            } else {
                photoButton.setImage(image, forState: UIControlState.Normal)
            }
            
            removeButton.hidden = (image == nil)
        }
    }
    
    // 代理
    weak var photoDelegate:PhotoSelectorViewCellDelegate?
    
    // MARK: - 按钮监听方法
    @objc func clickPhoto() {
        photoDelegate?.photoSelectorViewCellSelectPhoto(self)
    }
    
    @objc func clickRemove() {
        photoDelegate?.photoSelectorViewCellRemovePhoto(self)
    }
    
    // MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI() {
        addSubview(photoButton)
        addSubview(removeButton)
        
        // 自动布局
        photoButton.translatesAutoresizingMaskIntoConstraints = false
        photoButton.translatesAutoresizingMaskIntoConstraints = false
        
        let dict = ["photo": photoButton, "remove": removeButton]
        
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[photo]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[photo]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[remove]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[remove]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
      
        // 添加监听方法
        photoButton.addTarget(self, action: "clickPhoto", forControlEvents: UIControlEvents.TouchUpInside)
        removeButton.addTarget(self, action: "clickRemove", forControlEvents: UIControlEvents.TouchUpInside)
        
        photoButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
    }
    
    // MARK: - 懒加载
    private lazy var photoButton: UIButton = UIButton(imageName: "compose_pic_add")
    private lazy var removeButton: UIButton = UIButton(imageName: "compose_photo_close")
}